package com.handler;

import com.ymx.darling.bean.sql.SqlStatement;
import com.ymx.darling.build.mapper.MapperMethodInfoInfoManager;
import com.ymx.darling.build.mapper.method.ProviderMethodInfo;
import com.ymx.darling.session.Session;
import com.ymx.darling.wrapper.QueryWrapper;

import java.util.HashSet;
import java.util.List;

/**
 * @author 爱Java的小于
 */
public class SelectSet extends ProviderMethodInfo {
    /**
     * 自定义Mapper方法的具体执行逻辑
     * @param mapperClass 当前Mapper类 例如当前的类为UserMapper
     * @param session  Session
     * @param sqlStatementId sqlStatement的id
     * @param param 参数列表
     * @return Object 返回值
     * @throws Throwable 异常统一抛出
     */
    @Override
    public Object invoke(Class<?> mapperClass, Session session, String sqlStatementId, Object[] param) throws Throwable {
        // 根据接口获取实体类
        Class<?> entityType = MapperMethodInfoInfoManager.getEntityType(mapperClass);
        // 根据QueryWrapper构建sql
        QueryWrapper queryWrapper = (QueryWrapper) param[0];
        // 构建sql时需要根据当前实体内容构建 所以entityType不能为null
        SqlStatement select = queryWrapper.toSql(entityType);
        // 最终由session执行sql并返回
        List<?> entityList = session.selectList(entityType, select.getSql(), select.getParamList().toArray());
        return new HashSet<>(entityList);
    }
}
